package com.zcxy.edu.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zcxy.common.config.RuoYiConfig;
import com.zcxy.common.core.domain.entity.SysUser;
import com.zcxy.common.utils.DateUtils;
import com.zcxy.common.utils.http.HttpUtilsNew;
import com.zcxy.system.domain.SysConfig;
import com.zcxy.system.service.ISysConfigService;
import com.zcxy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zcxy.edu.mapper.EduStudentMapper;
import com.zcxy.edu.domain.EduStudent;
import com.zcxy.edu.service.IEduStudentService;

/**
 * 学生Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-20
 */
@Service
public class EduStudentServiceImpl implements IEduStudentService
{
    @Autowired
    private EduStudentMapper eduStudentMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysUserService sysUserService;

    private static final Logger log = LoggerFactory.getLogger(EduStudentServiceImpl.class);

    /**
     * 查询学生
     *
     * @param id 学生主键
     * @return 学生
     */
    @Override
    public EduStudent selectEduStudentById(Long id)
    {
        return eduStudentMapper.selectEduStudentById(id);
    }

    /**
     * 查询学生列表
     *
     * @param eduStudent 学生
     * @return 学生
     */
    @Override
    public List<EduStudent> selectEduStudentList(EduStudent eduStudent)
    {
        List<EduStudent> list = eduStudentMapper.selectEduStudentList(eduStudent);
        for(EduStudent eduStudent1 : list){
            SysUser sysUser = sysUserService.selectUserByUserName(eduStudent1.getXH());
            eduStudent1.setUserId(sysUser.getUserId());
        }
        return list;
    }

    /**
     * 新增学生
     *
     * @param eduStudent 学生
     * @return 结果
     */
    @Override
    public int insertEduStudent(EduStudent eduStudent)
    {
        EduStudent edu = new EduStudent();
        edu.setXH(eduStudent.getXH());
        List<EduStudent> eduStudentList = eduStudentMapper.selectEduStudentList(edu);
        if(eduStudentList.size() == 0){
            eduStudent.setCreateTime(DateUtils.getNowDate());
            return eduStudentMapper.insertEduStudent(eduStudent);
        }else{
            eduStudent.setId(eduStudentList.get(0).getId());
            eduStudent.setUpdateTime(DateUtils.getNowDate());
            return eduStudentMapper.updateEduStudent(eduStudent);
        }
    }

    /**
     * 修改学生
     *
     * @param eduStudent 学生
     * @return 结果
     */
    @Override
    public int updateEduStudent(EduStudent eduStudent)
    {
        eduStudent.setUpdateTime(DateUtils.getNowDate());
        return eduStudentMapper.updateEduStudent(eduStudent);
    }

    /**
     * 批量删除学生
     *
     * @param ids 需要删除的学生主键
     * @return 结果
     */
    @Override
    public int deleteEduStudentByIds(Long[] ids)
    {
        return eduStudentMapper.deleteEduStudentByIds(ids);
    }

    /**
     * 删除学生信息
     *
     * @param id 学生主键
     * @return 结果
     */
    @Override
    public int deleteEduStudentById(Long id)
    {
        return eduStudentMapper.deleteEduStudentById(id);
    }

    /**
     * 自动刷新数据
     */
    public void selectAndSaveApiData() throws UnsupportedEncodingException {
        String page = sysConfigService.selectConfigByKey("studentDataPage");
        int pageNumber = Integer.parseInt(page);

        String url = RuoYiConfig.getStudentPath();
        url += "?token="+sysConfigService.selectConfigByKey("eduToken");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id","239396f0549511ef1672576b3e52e1b5");
        jsonObject.put("pageIndex", pageNumber);
        jsonObject.put("params",new JSONArray(new JSONObject()));

        String encodedUrl = URLEncoder.encode(jsonObject.toJSONString(), StandardCharsets.UTF_8.toString());
        url += "&jsonStr="+encodedUrl;

        log.info("请求获取学生信息地址参数:"+url);
        String result = HttpUtilsNew.sendGet(url,"","",null);
        log.info("请求获取学生信息结果"+result);

        JSONObject resultData = JSONObject.parseObject(result);
        if(resultData.getInteger("status") != 200){
            return;
        }

        JSONObject data = resultData.getJSONObject("data");

        if(data.getInteger("totalCount")==eduStudentMapper.eduStudentCount()){
            return;
        }else{
            pageNumber++;
        }

        JSONArray jsonArray = data.getJSONArray("list");
        for(Object obj : jsonArray){
            JSONObject json = (JSONObject) obj;
            EduStudent eduStudent = JSON.toJavaObject(json, EduStudent.class);
            insertEduStudent(eduStudent);

            //插入用户表
            SysUser sysUser = new SysUser();
            sysUser.setUserName(eduStudent.getXH());
            sysUser.setNickName(eduStudent.getXM());
            sysUser.setCreateBy("定时任务");
            sysUser.setDelFlag("0");
            sysUser.setRemark("学生");

            Long[] roleIds = new Long[] {101l};
            sysUser.setRoleIds(roleIds);
            sysUserService.saveCenterUser(sysUser);
        }

        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey("studentDataPage");
        List<SysConfig> list = sysConfigService.selectConfigList(sysConfig);
        list.get(0).setConfigValue(pageNumber+"");
        sysConfigService.updateConfig(list.get(0));
    }
}
